package com.qn.example.controller;

import com.qn.example.pojo.R;
import com.qn.example.pojo.ShoppingCart;
import com.qn.example.service.impl.ShoppingCartServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/19 11:18
 */

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Resource
    private ShoppingCartServiceImpl shoppingCartService;


    @GetMapping("/list")
    public R list(HttpSession httpSession){
        Long user = (Long) httpSession.getAttribute("user");
        List<ShoppingCart> shoppingCartList =  shoppingCartService.list(user);
        return R.success(shoppingCartList);
    }

    @PostMapping("/add")
    public R addShopCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        Long user = (Long) session.getAttribute("user");
        shoppingCart.setUserId(user);
        //交给service去处理,添加完毕购物车之后，要求返回该购物项
        ShoppingCart sc  =  shoppingCartService.add(shoppingCart);
        return R.success(sc);
    }

    /**
     * 清空购物车
     * @param session
     * @return
     */
    @DeleteMapping("/clean")
    public R clean( HttpSession session){
        //1. 得到登陆者的id
        Long userId = (Long) session.getAttribute("user");
        //2. 根据id删除购物车
        shoppingCartService.clean(userId);
        return R.success("清空购物车");
    }

    /**
     * 减少购物车数量
     */
    @PostMapping("/sub")
    public R deleteShopCart(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        //获取当前登录用户的ID
        Long userId = (Long) session.getAttribute("user");
        //调用业务层添加购物车
        ShoppingCart sc  = shoppingCartService.deleteShoppingCart(shoppingCart.getDishId(),shoppingCart.getSetmealId(),userId);
        return  R.success(sc);
    }
}
